package netx

import (
	"fmt"
	"net"
	"strconv"

	"github.com/gookit/color"
)

var Ip = net.IPv4(0, 0, 0, 0)
var Port = 9960

func UdpClient(i int) {
	socket, err := net.DialUDP("udp", nil, &net.UDPAddr{
		IP:   net.IPv4(0, 0, 0, 0),
		Port: Port,
	})
	if err != nil {
		fmt.Println("连接服务端失败，err:", err)
		return
	}
	defer socket.Close()
	sendData := []byte("Hello server:" + strconv.Itoa(i))
	_, err = socket.Write(sendData) // 发送数据
	if err != nil {
		fmt.Println("发送数据失败，err:", err)
		return
	}
	data := make([]byte, 4096)
	n, remoteAddr, err := socket.ReadFromUDP(data) // 接收数据
	if err != nil {
		fmt.Println("接收数据失败，err:", err)
		return
	}
	fmt.Printf("recv:%v addr:%v count:%v\n", string(data[:n]), remoteAddr, n)

}
func UdpServer() {
	listenUDP, err := net.ListenUDP(
		"udp",
		&net.UDPAddr{
			IP:   Ip,
			Port: Port,
		},
	)
	if err != nil {
		panic(err)
	}
	defer listenUDP.Close()
	temp := make([]byte, 1024)
	for {
		size, addr, err := listenUDP.ReadFromUDP(temp)
		if err != nil {
			color.Redln(err)
			continue
		}
		fmt.Println(addr.Network(), addr.String(), string(temp[:size]))
		_, err = listenUDP.WriteToUDP(temp[:size], addr) // 发送数据
		if err != nil {
			fmt.Println("write to listenUDP failed, err:", err)
			continue
		}
	}
}
